<template>
  <div class="no-background-container">
    <el-affix :offset="0">
      <div class="qs-y-table-header">
        <div class="header-label">
          <div class="header-label-title">选择参会人员</div>
        </div>
        <div class="header-query">
          <div v-if="selectedUsers.length > 0" class="selected-summary">
            <div class="summary-content">
              <el-icon><user-filled /></el-icon>
              <span>已选择 {{ selectedUsers.length }} 人</span>
              <el-button link type="primary" @click="showSelectedDrawer = true">查看详情</el-button>
            </div>
            <div class="summary-actions">
              <el-button link type="danger" @click="handleClearAll">清空</el-button>
              <el-button :loading="submitting" type="primary" @click="onConfirmClick">确认添加</el-button>
              <el-button @click="handleCancel">返回</el-button>
            </div>
          </div>
          <div v-else class="header-actions">
            <el-button :disabled="selectedUsers.length === 0" :loading="submitting" type="primary" @click="onConfirmClick">
              确认添加
            </el-button>
            <el-button @click="handleCancel">返回</el-button>
          </div>
        </div>
      </div>
    </el-affix>

    <div class="page-content">
      <person-selector ref="selectorRef" @cancel="handleCancel" @confirm="handleConfirm" @selection-change="handleSelectionChange" />
    </div>

    <!-- 已选人员抽屉 -->
    <el-drawer v-model="showSelectedDrawer" destroy-on-close size="30%" title="已选择人员列表" :with-header="true">
      <div class="drawer-header">
        <div class="drawer-title">
          <span>共 {{ selectedUsers.length }} 人</span>
          <el-button link type="danger" @click="handleClearAll">清空</el-button>
        </div>
        <el-input v-model="selectedSearchKeyword" clearable placeholder="搜索已选人员" :prefix-icon="Search" />
      </div>

      <el-scrollbar height="calc(100vh - 240px)">
        <div v-if="filteredSelectedUsers.length > 0" class="selected-list">
          <div v-for="user in filteredSelectedUsers" :key="user.id" class="selected-item">
            <div class="user-info">
              <el-avatar class="user-avatar" size="small">{{ user.name.substring(0, 1) }}</el-avatar>
              <div class="user-details">
                <span class="user-name">{{ user.name }}</span>
                <span class="user-dept">{{ user.department }}</span>
              </div>
            </div>
            <el-button link size="small" type="danger" @click="handleRemoveUser(user)">移除</el-button>
          </div>
        </div>
        <el-empty v-else description="暂无已选人员" />
      </el-scrollbar>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { Search, UserFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import PersonSelector from './components/PersonSelector.vue'
import type { User } from './components/types'
import { moduleApi } from './config'
import Public from '/@/api/public'

const router = useRouter()
const selectorRef = ref()
const selectedUsers = ref<User[]>([])
const showSelectedDrawer = ref(false)
const selectedSearchKeyword = ref('')
const submitting = ref(false)

// 过滤已选用户
const filteredSelectedUsers = computed(() => {
  if (!selectedSearchKeyword.value) return selectedUsers.value

  return selectedUsers.value.filter(
    (user) =>
      user.name.includes(selectedSearchKeyword.value) ||
      user.department.includes(selectedSearchKeyword.value) ||
      user.position.includes(selectedSearchKeyword.value)
  )
})

// 处理选择变化
const handleSelectionChange = (users: User[]) => {
  selectedUsers.value = users
}

// 移除选中的用户
const handleRemoveUser = (user: User) => {
  selectedUsers.value = selectedUsers.value.filter((item) => item.id !== user.id)
  // 同步到选择器组件中
  selectorRef.value?.removeUser(user.id)
}

// 清空所有选中的用户
const handleClearAll = () => {
  selectedUsers.value = []
  selectorRef.value?.clearSelection()
  showSelectedDrawer.value = false
}

// 返回上一页
const handleBack = () => {
  router.go(-1)
}

// 返回列表页
const goToList = () => {
  // 返回参会人列表
  router.back()
}

// UI 按钮点击事件
const onConfirmClick = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择至少一位参会人员')
    return
  }

  // 确认提交
  ElMessageBox.confirm(`确认添加选中的 ${selectedUsers.value.length} 名人员作为参会人员?`, '确认提交', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'info',
  })
    .then(() => {
      handleConfirm()
    })
    .catch(() => {})
}

// 确认选择并提交
const handleConfirm = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择至少一位参会人员')
    return
  }

  submitting.value = true
  try {
    // 获取活动ID
    const activityId = localStorage.getItem('hongyouActId')

    // 将所有选中的用户ID拼接为逗号分隔的字符串，参照dialog.vue的提交方式
    const selectedIds = selectedUsers.value.map((user) => user.id).join(',')
    console.log('selectedIds', selectedIds)

    // 构造提交数据格式
    const data = { userId: selectedIds, activityId }

    // 一次性提交所有选中的用户ID
    const response = await Public.addApi({ url: moduleApi, data })

    // 处理提交结果
    const responseData = response.data || response
    if (responseData && responseData.code === 0) {
      // 提示成功，并询问下一步操作
      ElMessageBox.confirm(`成功添加 ${selectedUsers.value.length} 名参会人员。是否返回参会人列表?`, '添加成功', {
        confirmButtonText: '返回列表',
        cancelButtonText: '继续添加',
        type: 'success',
      })
        .then(() => {
          // 返回参会人列表
          goToList()
        })
        .catch(() => {
          // 继续添加，清空当前选择
          handleClearAll()
        })
    } else {
      ElMessage.error('添加参会人员失败')
    }
  } catch (error) {
    console.error('提交过程出错:', error)
    ElMessage.error('添加参会人员失败')
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  if (selectedUsers.value.length > 0) {
    ElMessageBox.confirm('您已选择了人员但尚未提交，确定要返回吗?', '确认返回', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        handleBack()
      })
      .catch(() => {})
  } else {
    handleBack()
  }
}
</script>

<style scoped>
.page-content {
  margin-top: 16px;
  flex: 1;
  overflow: hidden;
  height: calc(100vh - 120px);
}

.selected-summary {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #f0faff;
  border-radius: 4px;
  width: 100%;
  border: 1px dashed #409eff;
}

.summary-content {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #409eff;
  font-weight: 500;
}

.summary-content .el-icon {
  font-size: 18px;
}

.summary-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.drawer-header {
  padding: 0 12px 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.drawer-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-weight: 500;
}

.selected-list {
  padding: 0 12px;
}

.selected-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 8px;
  border-bottom: 1px solid #ebeef5;
}

.selected-item:last-child {
  border-bottom: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 500;
  font-size: 14px;
}

.user-dept {
  font-size: 12px;
  color: #909399;
}

.user-avatar {
  background-color: #409eff;
  color: #fff;
}

.header-query {
  display: flex;
  align-items: center;
  width: 100%;
}
</style>
